package com.py.credit.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.DeclarationManagement;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.DeclarationManagementEnum;
import com.py.credit.service.DeclarationManagementService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping("/declarationManagement")
public class DeclarationManagementController {

	// 列表
	private static final String SECLARARIONMANAGEMRNT = "declaration_management";
	@Autowired
	private DeclarationManagementService declarationManagementService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@RequestMapping(value = "/getCountColums.json")
	public RestServiceResult<List<OptionalColumn>> getCountColums() {
		return new RestServiceResult<List<OptionalColumn>>(DeclarationManagementEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getDefaultCountColums.json")
	public RestServiceResult<List<String>> getDefaultCountColums() {
		return new RestServiceResult<List<String>>(DeclarationManagementEnum.getDefaultShowColumnEN());
	}

	@RequestMapping(value = "/getAdvancedCountColums.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedCountColums() {
		return new RestServiceResult<List<OptionalColumn>>(DeclarationManagementEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("declarationManagement#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
			String column = StringUtils.join(columns, ",");
			MapCache.set(userInfo.getId() + "_" + SECLARARIONMANAGEMRNT, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/export")
	public RestServiceResult<List<Map<String, Object>>> exportData(
			@RequestParam(value = "root_id", defaultValue = "", required = true) String root_id,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<OptionalColumn> optionalColumns = DeclarationManagementEnum.getOptionalColumns();
		List<Map<String, Object>> data;
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("declarationManagement#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			data = declarationManagementService.selectTableListByConditionForPage(root_id, showColumns, null, condition,
					page);
			result.setCount(page.getTotalCount());
			if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
				return result;
			}
			ExcelUtil.downloadExcel(response, data, "申报管理列表列表", "申报管理列表列表", showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("申报管理列表列表导出异常，请稍后再试！");
			ExceptionLogger.error("申报管理列表列表导出异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/selectTableListByConditionForPage.json")
	public RestServiceResult<List<Map<String, Object>>> selectTableListByConditionForPage(
			@RequestParam(value = "root_id", defaultValue = "", required = true) String root_id,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return r;
			}
		} else {
			r.setCode(user.getCode());
			r.setMsg(user.getMsg());
			return r;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + SECLARARIONMANAGEMRNT);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? DeclarationManagementEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		List<Map<String, Object>> data;
		try {
			rep = declarationManagementService.selectTableListByConditionForPage(root_id, showColumns, null, condition,
					page);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg(e.getMessage());
			ExceptionLogger.error("declarationManagement#selectTableListByConditionForPage", "报告信息查询失败");
		}
		r.setData(rep);
		return r;
	}

	/**
	 * 查询出所有的申报类型
	 * 
	 * @param type
	 * @param root_id
	 * @param id
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/selectForPage.json", method = RequestMethod.POST)
	public RestServiceResult<List<DeclarationManagement>> selectForPage(
			@RequestParam(value = "type", defaultValue = "", required = false) String type,
			@RequestParam(value = "root_id", defaultValue = "", required = false) String root_id,
			@RequestParam(value = "id", defaultValue = "", required = false) String id, Page page) {
		RestServiceResult<List<DeclarationManagement>> result = new RestServiceResult<List<DeclarationManagement>>();
		List<DeclarationManagement> tableList = declarationManagementService.selectForPage(type, page, id, root_id);
		result.setData(tableList);
		result.setCount(page.getTotalCount());
		return result;

	}

	/**
	 * 修改
	 * 
	 * @param declarationManagement
	 * @return
	 */
	@RequestMapping(value = "/updateById.do", method = RequestMethod.POST)
	public RestServiceResult<Object> updateById(@RequestBody DeclarationManagement declarationManagement) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		declarationManagementService.updateById(declarationManagement.getType(), declarationManagement.getId(),
				declarationManagement.getRoot_id(), declarationManagement.getState());
		result.setMsg("编辑成功");
		return result;

	}

	/**
	 * 删除
	 * 
	 * @param strId
	 * @return
	 */
	@RequestMapping("/delListById.do")
	public RestServiceResult<Object> delListById(
			@RequestParam(value = "ids", defaultValue = "", required = false) String strId) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		List<String> idList = new ArrayList<String>();
		idList = java.util.Arrays.asList(strId.split(","));
		declarationManagementService.delListById(idList);
		result.setMsg("删除成功");
		return result;

	}

	/**
	 * 查询是否已存在
	 * 
	 * @param type
	 * @param root_id
	 * @return
	 */
	@RequestMapping("/selectIsExist.json")
	public RestServiceResult<Object> selectIsExist(
			@RequestParam(value = "type", defaultValue = "", required = false) String type,
			@RequestParam(value = "root_id", defaultValue = "", required = false) String root_id) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		DeclarationManagement declarationManagement = declarationManagementService.selectIsExist(type, root_id);
		result.setData(declarationManagement);
		result.setCode(result.CODE_SUCCESS);
		return result;

	}

	/**
	 * 添加
	 * 
	 * @param declarationManagement
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/insert.do", method = RequestMethod.POST)
	public RestServiceResult<Object> insert(@RequestBody DeclarationManagement declarationManagement,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser usrInfo = new SysUser();
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			usrInfo = user.getData();
		}

		RestServiceResult<Object> result = new RestServiceResult<Object>();
		declarationManagementService.insert(String.valueOf(usrInfo.getRealName()), declarationManagement.getRoot_id(),
				declarationManagement.getType());
		result.setMsg("添加成功");
		return result;

	}

	/**
	 * 计算申报资源目录数
	 * 
	 * @param cube_id_list
	 * @param id
	 * @param finance_id_list
	 * @return
	 */
	@RequestMapping(value = "/updateIdCountListById.do", method = RequestMethod.POST)
	public RestServiceResult<Object> updateIdCountListById(
			@RequestParam(value = "cube_id_list", defaultValue = "[]", required = false) String cube_id_list,
			@RequestParam(value = "id", defaultValue = "", required = false) String id,
			@RequestParam(value = "finance_id_list", defaultValue = "[]", required = false) String finance_id_list) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		List<Map<String, String>> cube_id_lists = JSON.parseObject(cube_id_list,
				new TypeReference<List<Map<String, String>>>() {
				});
		StringBuilder str = new StringBuilder();
		for (Map a : cube_id_lists) {
			str.append(a.get("tableId") + ",");
		}
		List<Map<String, String>> finance_id_lists = JSON.parseObject(finance_id_list,
				new TypeReference<List<Map<String, String>>>() {
				});
		StringBuilder strs = new StringBuilder();
		for (Map a : finance_id_lists) {
			strs.append(a.get("tableId") + ",");
		}
		declarationManagementService.updateIdCountListById(String.valueOf(str), id, String.valueOf(strs));
		result.setMsg("分配成功");
		return result;

	}

	/*
	 * @RequestMapping(value="/updateIdCountListById.do", method =
	 * RequestMethod.POST) public RestServiceResult<Object>
	 * updateIdCountListById(
	 * 
	 * @RequestParam(value = "cube_id_list", required = true) String
	 * cube_id_list,
	 * 
	 * @RequestParam(value = "id", required = true) String id,
	 * 
	 * @RequestParam(value = "finance_id_list", required = true) String
	 * finance_id_list){ RestServiceResult<Object> result = new
	 * RestServiceResult<Object>(); List<Map<String, String>> cube_id_lists =
	 * null; StringBuilder str=new StringBuilder(); str.append("");
	 * if(finance_id_list.equals("F")) { cube_id_lists =
	 * JSON.parseObject(cube_id_list, new TypeReference<List<Map<String,
	 * String>>>() { }); for(Map a:cube_id_lists) {
	 * str.append(a.get("tableId")+","); } }
	 * 
	 * List<Map<String, String>> finance_id_lists = null; StringBuilder strs=new
	 * StringBuilder(); strs.append(""); if(cube_id_list.equals("C")) {
	 * finance_id_lists = JSON.parseObject(finance_id_list, new
	 * TypeReference<List<Map<String, String>>>() { }); for(Map
	 * a:finance_id_lists) { strs.append(a.get("tableId")+","); } }
	 * 
	 * declarationManagementService.updateIdCountListById(str.toString(),
	 * id,strs.toString()); result.setMsg("分配成功"); return result;
	 * 
	 * }
	 */
	/**
	 * 查询出信用申报的表
	 * 
	 * @param collection_type
	 * @param finance_id_list
	 * @return
	 */
	@RequestMapping(value = "/selectXypjTable.json", method = RequestMethod.POST)
	public RestServiceResult<List<DeclarationManagement>> selectXypjTable(
			@RequestParam(value = "collection_type", defaultValue = "", required = false) String collection_type,
			@RequestParam(value = "finance_id_list", defaultValue = "", required = false) String finance_id_list) {
		RestServiceResult<List<DeclarationManagement>> result = new RestServiceResult<List<DeclarationManagement>>();
		List<DeclarationManagement> tableList = declarationManagementService.selectXypjTable(collection_type);
		List<String> idList = new ArrayList<String>();
		if (finance_id_list.isEmpty()) {
			result.setData(tableList);
			return result;
		} else {
			idList = java.util.Arrays.asList(finance_id_list.split(","));
			for (DeclarationManagement a : tableList) {
				for (int i = 0; i < idList.size(); i++) {
					if (a.getCube_id().equals(idList.get(i))) {
						a.setChecked(true);
					}
				}

			}
		}
		result.setData(tableList);
		return result;
	}

	/**
	 * 查询出已配置的表
	 * 
	 * @param root_id
	 * @param collection_type
	 * @param finance_id_list
	 * @return
	 */
	@RequestMapping("/selectTable.json")
	public RestServiceResult selectTable(
			@RequestParam(value = "kId", defaultValue = "", required = false) String root_id,
			@RequestParam(value = "collection_type", defaultValue = "", required = false) String collection_type,
			@RequestParam(value = "finance_id_list", defaultValue = "", required = false) String finance_id_list) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		if (finance_id_list.isEmpty()) {
			return result;
		} else {
			List<String> idList = new ArrayList<String>();
			idList = java.util.Arrays.asList(finance_id_list.split(","));
			List<DeclarationManagement> data = declarationManagementService.selectTable(idList);
			for (DeclarationManagement a : data) {
				a.setChecked(true);
			}
			result.setData(data);
		}
		return result;
	}

}
